import superagent from 'superagent';
import globalConfig from "./config";
import {MessageBox} from "element-ui";
import store from "../vuex/store";
// import Logger from '../common/js/Logger';

// let logger = new Logger('Ajax');
/**
 * 内部方法, 在superagent api的基础上, 包装一些全局的设置
 *
 * @param method 要请求的方法
 * @param url 要请求的url
 * @param data 要发送的数据 - GET
 * @param params url上的额外参数 - POST
 * @returns {Promise}
 */

async function requestWrapper(method, url, data, params) {
    // logger.debug('method=%s, url=%s, params=%o, data=%o, headers=%o', method, url, params, data);
    const  that=this;
    return new Promise((resolve, reject) => {
        const tmp = superagent(method, url);
        // 跨域请求
        tmp.withCredentials();
        // 设置全局的超时时间
        if (globalConfig.api.timeout && !isNaN(globalConfig.api.timeout)) {
            tmp.timeout(globalConfig.api.timeout);
        }
        // 默认的Content-Type和Accept
        tmp.set('Access-Control-Allow-Origin', '*');
        tmp.set('Access-Control-Allow-Credentials', 'true');
        tmp.set('Access-Control-Allow-Methods', 'GET, HEAD, POST, PUT, DELETE, OPTIONS');
        const token = sessionStorage.getItem('token');
        if (undefined !== token && null !== token) {
            tmp.set('token', token);
        }
        // url中是否有附加的参数?
        if (method == 'GET') {
            // tmp.set('Accept', 'application/json');
            tmp.query(params);
        }
        // body中发送的数据?
        if (method == 'POST') {
            /*if (url.indexOf("gt") !== -1 || url.indexOf("login") !== -1) {
                tmp.set('Content-Type', 'application/x-www-form-urlencoded');
            } */
            tmp.set('Content-Type', 'application/x-www-form-urlencoded');
            tmp.send(data);
        }
        // tmp.type('form');
        // 包装成promise
        tmp.end((err, res) => {
            // logger.debug('err=%o, res=%o', err, res);
            // 我本来在想, 要不要在这里把错误包装下, 即使请求失败也调用resolve, 这样上层就不用区分"网络请求成功但查询数据失败"和"网络失败"两种情况了
            // 但后来觉得这个ajax方法是很底层的, 在这里包装不合适, 应该让上层业务去包装
            if ((res && res.body)) {
                resolve(res.body);
           /* } else if(res && res.text) {*/
               /* let resu = JSON.parse(res.text);
                if (resu.data.hasOwnProperty(401)) {
                    MessageBox.confirm(
                        '登录状态已过期，您可以继续留在该页面，或者重新登录',
                        '系统提示',
                        {
                            confirmButtonText: '重新登录',
                            cancelButtonText: '取消',
                            type: 'warning'
                        }
                    ).then(() => {
                        resolve(res.text);
                        // this.$router.push('/login');
                        that.$router.push("/login")
                       /!* this.$store.dispatch('login').then(() => {
                            // 为了重新实例化vue-router对象 避免bug
                            location.reload()
                        })*!/
                    })
                }*/
            }else {
                reject(err || res);
            }
        });
    }).catch((e) => {
        console.info("retun promise error ,url-["+url+"], E:↓:");
        if(JSON.stringify(url).indexOf("/gt/") === -1){
            console.error(e);
            return;
        }
        return new Promise((resolve,reject)=>{
            resolve(JSON.parse(e.text));
        });
    });
}

// regiontest
export const getRegionInfoByPage= params => {
    return requestWrapper('GET', `${globalConfig.getAPIPath()}${globalConfig.region.list}`, null, params);
};

//geeTest
export const geeTestRegister = params => {
    return requestWrapper('GET', `${globalConfig.getAPIPath()}${globalConfig.geeTest.register}`, null, params);
};
export const geeTestValidate = data => {
    return requestWrapper('POST', `${globalConfig.getAPIPath()}${globalConfig.geeTest.validate}`, data, null);
};
//客户
export const getCustomersByPage = params => {
    return requestWrapper('GET', `${globalConfig.getAPIPath()}${globalConfig.customer.getCustomerList}`, null, params);
};
export const delCustomer = data => {
    return requestWrapper('POST', `${globalConfig.getAPIPath()}${globalConfig.customer.delCustomer}`, data, null);
};

// get ipHost
export const getIpHost = params => {
    return requestWrapper('GET', `http://pv.sohu.com/cityjson`, null, null);
};
//统计信息
export const getDashboardInfo = params => {
    return requestWrapper('GET', `${globalConfig.getAPIPath()}${globalConfig.dashboard.info}`, null, params);
};
export const getDashboardInfoList = params => {
    return requestWrapper('GET', `${globalConfig.getAPIPath()}${globalConfig.dashboard.infolist}`, null, params);
};

// user
export const requestLogin = data => {
    return requestWrapper('POST', `${globalConfig.getAPIPath()}${globalConfig.user.login}`, data, null);
};
export const requestLogout = data => {
    return requestWrapper('POST', `${globalConfig.getAPIPath()}${globalConfig.user.logout}`, null, null);
};


export const getUserListPage = params => {
    return requestWrapper('GET', `${globalConfig.getAPIPath()}${globalConfig.user.getUserList}`, null, params);
};
export const delUser = data => {
    return requestWrapper('POST', `${globalConfig.getAPIPath()}${globalConfig.user.delUser}`, data, null);
};
export const batchRemoveUser = data => {
    return requestWrapper('POST', `${globalConfig.getAPIPath()}${globalConfig.user.batchRemove}`, data, null);
};
export const addUser = data => {
    return requestWrapper('POST', `${globalConfig.getAPIPath()}${globalConfig.user.addUser}`, data, null);
};
export const editUser = data => {
    return requestWrapper('POST', `${globalConfig.getAPIPath()}${globalConfig.user.editUser}`, data, null);
};



//任务列表
export const getJobListPage = data => {
    return requestWrapper('GET', `${globalConfig.getAPIPath()}${globalConfig.job.getJobList}`, null, data);
};
export const editJob = data => {
    return requestWrapper('POST', `${globalConfig.getAPIPath()}${globalConfig.job.editJob}`, data, null);
};
export const pauseJob = data => {
    return requestWrapper('POST', `${globalConfig.getAPIPath()}${globalConfig.job.pauseJob}`, data, null);
};
export const resumeJob = data => {
    return requestWrapper('POST', `${globalConfig.getAPIPath()}${globalConfig.job.resumeJob}`, data, null);
};
export const addJob = data => {
    return requestWrapper('POST', `${globalConfig.getAPIPath()}${globalConfig.job.addJob}`, data, null);
};
export const registerGt = data => {
    return  requestWrapper('GET', `${globalConfig.getAPIPath()}${globalConfig.gt.getJobList}`,null , data);
};
//sys - log
export const sysLogList = data => {
    return  requestWrapper('GET', `${globalConfig.getAPIPath()}${globalConfig.sysLog.logList}`, null, data);
};
//sys - role
export const sysRoleList = data => {
    return  requestWrapper('GET', `${globalConfig.getAPIPath()}${globalConfig.sysRole.roleList}`, null, data);
};
export const sysRoleSelect = data => {
    return  requestWrapper('GET', `${globalConfig.getAPIPath()}${globalConfig.sysRole.roleSelect}`, data, null);
};
export const sysRoleInfo = data => {
    return  requestWrapper('GET', `${globalConfig.getAPIPath()}${globalConfig.sysRole.roleInfo}`, null, data);
};
export const sysRoleAdd = data => {
    return  requestWrapper('POST', `${globalConfig.getAPIPath()}${globalConfig.sysRole.roleAdd}`, data, null);
};
export const sysRoleUpdate = data => {
    return  requestWrapper('POST', `${globalConfig.getAPIPath()}${globalConfig.sysRole.roleUpdate}`, data, null);
};
export const sysRoleDelete = data => {
    return  requestWrapper('POST', `${globalConfig.getAPIPath()}${globalConfig.sysRole.roleDelete}`, data, null);
};
//sys - menu
export const sysMenuList = data => {
    return  requestWrapper('GET', `${globalConfig.getAPIPath()}${globalConfig.sysMenu.menuList}`, data, null);
};
export const sysMenuNav = data => {
    return  requestWrapper('GET', `${globalConfig.getAPIPath()}${globalConfig.sysMenu.menuNav}`, data, null);
};export const sysMenuDel = data => {
    return  requestWrapper('POST', `${globalConfig.getAPIPath()}${globalConfig.sysMenu.menuDelete}`, data, null);
};
export const sysMenuInfo = data => {
    return  requestWrapper('POST', `${globalConfig.getAPIPath()}${globalConfig.sysMenu.menuInfo}`, data, null);
};export const sysMenuUpdate = data => {
    return  requestWrapper('POST', `${globalConfig.getAPIPath()}${globalConfig.sysMenu.menuUpdate}`, data, null);
};
export const sysMenuSelect = data => {
    return  requestWrapper('GET', `${globalConfig.getAPIPath()}${globalConfig.sysMenu.menuSelect}`, null, data);
};
//proxy
export const proxyList = data => {
    return  requestWrapper('GET', `${globalConfig.getAPIPath()}${globalConfig.proxy.proxyList}`, null, data);
}





